package com.example.demo.juc;

/**
 * 每一个ThreadLocal都有有一个ThreadLocal.ThreadLocalMap对象
 * 当调用一个ThreadLocal的set(T value)方法时,先得到当前线程的ThreadLocalMap对象,
 * 然后将Threadlocal->value的键值对插入该Map中
 *
 * ThreadLocal从理论上来讲并不是用来解决并发问题,因为根本原因不存在多线程竞争
 * 在一些场景(尤其是使用线程池)下,由于ThreadLocal.ThreadlocalMap的底层数据结构导致,ThreadLocaly
 * 有存在泄漏的情况,应该尽可能在每次使用ThreadLocal后手动调用,remove(),以避免出现ThreadLocal经典的内存
 * 经典的内存泄漏甚至是造成自身业务出现混乱的风险.
 */
public class ThreadLocalExample1 {
    public static void main(String[] args) {

        ThreadLocal threadLocal1 = new ThreadLocal();
        ThreadLocal threadLocal2 = new ThreadLocal();

        Thread thread = new Thread(() -> {
            threadLocal1.set(1);
            threadLocal2.set(1);
        });

        Thread thread1 = new Thread(() -> {
            threadLocal1.set(2);
            threadLocal2.set(2);
        });
        thread.start();
        thread1.start();
    }
}
